package fr.smile.liferay.portlet;

import java.io.IOException;
import java.util.Calendar;

import javax.portlet.ActionRequest;
import javax.portlet.ActionResponse;
import javax.portlet.GenericPortlet;
import javax.portlet.PortletConfig;
import javax.portlet.PortletContext;
import javax.portlet.PortletException;
import javax.portlet.PortletMode;
import javax.portlet.PortletRequestDispatcher;
import javax.portlet.RenderRequest;
import javax.portlet.RenderResponse;
import javax.servlet.http.HttpServletRequest;

import com.liferay.counter.service.CounterLocalServiceUtil;
import com.liferay.portal.kernel.exception.PortalException;
import com.liferay.portal.kernel.exception.SystemException;
import com.liferay.portal.kernel.upload.UploadPortletRequest;
import com.liferay.portal.kernel.util.GetterUtil;
import com.liferay.portal.kernel.util.ParamUtil;
import com.liferay.portal.kernel.util.StringUtil;
import com.liferay.portal.util.PortalUtil;

import fr.smile.liferay.portlet.news.model.NewsEntry;
import fr.smile.liferay.portlet.news.service.NewsEntryLocalServiceUtil;

public class SamplePortlet extends GenericPortlet {

	private static final String EDIT_PAGE_PARAM = "edit-jsp";
	// private static final String HELP_PAGE_PARAM = "help-jsp";
	private static final String VIEW_PAGE_PARAM = "view-jsp";

	public void init(PortletConfig config) throws PortletException {
		super.init(config);
		super.init(config);
	}

	public void doEdit(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {

		PortletContext context = getPortletContext();
		PortletRequestDispatcher rd = context
				.getRequestDispatcher(getInitParameter(EDIT_PAGE_PARAM));
		rd.include(request, response);
	}

	public void doView(RenderRequest request, RenderResponse response)
			throws PortletException, IOException {

		PortletContext context = getPortletContext();

		String cmd = ParamUtil.getString(request, "cmd");
		if ("edit".equals(cmd) || "preview".equals(cmd)) {
			long entryId = ParamUtil.getLong(request, "entryId");
			try {
				NewsEntry entry = NewsEntryLocalServiceUtil
						.getNewsEntry(entryId);
				if (entry != null) {
					request.setAttribute("NewsEntry", entry);
				}
			} catch (Exception e) {
				// TODO - add error message
			}
		}
		PortletRequestDispatcher rd = context
				.getRequestDispatcher(getInitParameter(VIEW_PAGE_PARAM));
		if (rd != null)
			rd.include(request, response);
	}

	public void processAction(ActionRequest request, ActionResponse response)
			throws PortletException, IOException { 
		
		String cmd = null;
		String redirect = null;
		UploadPortletRequest uploadRequest = null;
		String contentType = request.getContentType();
		if (contentType.startsWith("multipart/form-data")) {
			uploadRequest = PortalUtil.getUploadPortletRequest(request);
			cmd = ParamUtil.getString(uploadRequest, "cmd");
			redirect = ParamUtil.getString(uploadRequest, "redirect");
		} else {
			cmd = ParamUtil.getString(request, "cmd");
			redirect = ParamUtil.getString(request, "redirect");
		}
		if (cmd == null) return;

		if (cmd.equals("delete")) {
			// delete Entry
			try {
				long entryId = ParamUtil.getLong(request, "entryId", 0);
				if (entryId > 0) {
					NewsEntryLocalServiceUtil.deleteEntry(entryId);
				}
			} catch (Exception e) {
				e.printStackTrace();
			} 
		} else if ("add".equalsIgnoreCase(cmd) || "update".equalsIgnoreCase(cmd)) {
			try {
				storeEntry(uploadRequest);
			} catch (Exception e) {
				e.printStackTrace(); // TODO
			}
		}
		if (redirect != null) response.sendRedirect(redirect);

	}

	private void storeEntry(HttpServletRequest request) throws Exception {

		long entryId = ParamUtil.getLong(request, "entryId", 0);

		String[] distributionScopeParts = StringUtil.split(ParamUtil.getString(
				request, "distributionScope"));

		long classNameId = 0;
		long classPK = 0;

		if (distributionScopeParts.length == 2) {
			classNameId = GetterUtil.getLong(distributionScopeParts[0]);

			if (classNameId > 0) {
				classPK = GetterUtil.getLong(distributionScopeParts[1]);
			}
		}

		long userId = ParamUtil.getLong(request, "userId");
		String title = ParamUtil.getString(request, "title");
		String content = ParamUtil.getString(request, "content");
		String description = ParamUtil.getString(request, "description");

		int displayDateMonth = ParamUtil
				.getInteger(request, "displayDateMonth");
		int displayDateDay = ParamUtil.getInteger(request, "displayDateDay");
		int displayDateYear = ParamUtil.getInteger(request, "displayDateYear");
		int displayDateHour = ParamUtil.getInteger(request, "displayDateHour");
		int displayDateMinute = ParamUtil.getInteger(request,
				"displayDateMinute");
		int displayDateAmPm = ParamUtil.getInteger(request, "displayDateAmPm");

//		if (displayDateAmPm == Calendar.PM) {
//			displayDateHour += 12;
//		}

		int expirationDateMonth = ParamUtil.getInteger(request,
				"expirationDateMonth");
		int expirationDateDay = ParamUtil.getInteger(request,
				"expirationDateDay");
		int expirationDateYear = ParamUtil.getInteger(request,
				"expirationDateYear");
		int expirationDateHour = ParamUtil.getInteger(request,
				"expirationDateHour");
		int expirationDateMinute = ParamUtil.getInteger(request,
				"expirationDateMinute");
		int expirationDateAmPm = ParamUtil.getInteger(request,
				"expirationDateAmPm");

//		if (expirationDateAmPm == Calendar.PM) {
//			expirationDateHour += 12;
//		}

		// get dates
		Calendar displayDate = Calendar.getInstance();
		displayDate.set(Calendar.DATE, displayDateDay);
		displayDate.set(Calendar.MONTH, displayDateMonth);
		displayDate.set(Calendar.YEAR, displayDateYear);
		displayDate.set(Calendar.AM_PM, displayDateAmPm);
		displayDate.set(Calendar.HOUR, displayDateHour);
		displayDate.set(Calendar.MINUTE, displayDateMinute);

		Calendar expDate = Calendar.getInstance();
		expDate.set(Calendar.DATE, expirationDateDay);
		expDate.set(Calendar.MONTH, expirationDateMonth);
		expDate.set(Calendar.YEAR, expirationDateYear);
		expDate.set(Calendar.AM_PM, expirationDateAmPm);
		expDate.set(Calendar.HOUR, expirationDateHour);
		expDate.set(Calendar.MINUTE, expirationDateMinute);

		try {
			if (entryId == 0) {
				NewsEntryLocalServiceUtil.addEntry(userId, classNameId,
						classPK, title, description, content,
						displayDate.getTime(), expDate.getTime());
			} else {
				NewsEntryLocalServiceUtil.updateEntry(entryId, title,
						description, content, displayDate.getTime(),
						expDate.getTime());
			}
		} catch (SystemException e) {
			e.printStackTrace();
		}
	}
}
